package cglib;

import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @program: Spring_day03_04_综合案例
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-29 17:59
 **/
public class UserServiceCglibProxy {

    public static UserServiceImpl createUserServiceCglibProxy(
            Class<UserServiceImpl> userServiceClass) {
        try {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(userServiceClass);

            // UserServiceImpl userService1 = userServiceClass.getConstructor().newInstance();
            Callback callback = new MethodInterceptor() {
                @Override
                public Object intercept(Object o, Method method, Object[] objects,
                                        MethodProxy methodProxy) throws Throwable {

                    //代理出来的对象o
                    if ("save".equals(method.getName())) {
                        System.out.println(o.getClass());

                        //原来类 不能调用,不然会递归停不下来
                        // method.invoke(o, objects);
                        //子类
                        Object invoke = methodProxy.invokeSuper(o, objects);
                        // System.out.println(invoke);
                        System.out.println("cglib还不熟");
                        return invoke;
                    } else {
                        return methodProxy.invokeSuper(o, objects);

                    }
                }
            };
            enhancer.setCallback(callback);

            UserServiceImpl o = (UserServiceImpl) enhancer.create();
            return o;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return null;
    }
}
